<template>
  <div>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增</a-button>
        <a-button @click="handleOpenCashierConfig"> 配置收银台支付 </a-button>
        <a-button @click="handleTennatBindPayMchApp" v-if="!userStore.getSelectTenant.payAppId"> 初始化租户绑定商户应用 </a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getActions(record)" />
      </template>
    </BasicTable>
    <DetailModal @register="register" />
    <MchDrawer @register="registerMchDrawer" @success="reload" />
    <PayIfConfigDrawer @register="registerPayIfConfig" @success="reload" />
    <CashierConfig @register="registerCashierConfig" />
  </div>
</template>
<script lang="ts" name="PayMchAppList" setup>
  import { ref, unref, toRaw } from "vue"
  import { BasicTable, TableAction } from "/@/components/Table"
  import { useDrawer } from "/@/components/Drawer"
  import { useModal } from "/@/components/Modal"
  import DetailModal from "./DetailModal.vue"
  import MchDrawer from "./MchDrawer.vue"
  import PayIfConfigDrawer from "./PayIfConfigListDrawer.vue"
  import CashierConfig from "./CashierConfig.vue"
  import { useGlobSetting } from "/@/hooks/setting"
  import { columns, searchFormSchema } from "./mchApp.data"
  import { listMchApp, deleteMchApp, batchDeleteMchApp, currentTenantBindApp } from "/@/api/pay"
  import { useListPage } from "/@/hooks/system/useListPage"
  import { useRouter } from "vue-router"
  import { useUserStore } from "/@/store/modules/user"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Icon } from "/@/components/Icon"

  const userStore = useUserStore()
  const { createMessage } = useMessage()
  const router = useRouter()
  let mchNo = router.currentRoute.value.query?.mchNo
  console.log("currentRoute.params , mchNo: " + mchNo)
  mchNo = mchNo == undefined ? "" : mchNo

  const glob = useGlobSetting()
  const [registerCashierConfig, { openModal: openCashierConfig }] = useModal()
  const [register, { openDrawer: openDetail }] = useDrawer()
  const [registerMchDrawer, { openDrawer: openMchDrawer }] = useDrawer()
  const [registerPayIfConfig, { openDrawer: openPayIfConfigDrawer }] = useDrawer()
  // 列表页面公共参数、方法
  const { prefixCls, tableContext } = useListPage({
    designScope: "PayMchAppList",
    tableProps: {
      title: "商户应用列表",
      beforeFetch: (params) => {
        params.mchNo = !params.mchNo ? mchNo : params.mchNo
      },
      api: listMchApp,
      columns: columns,
      bordered: false,
      actionColumn: {
        width: 185,
        title: "操作",
        dataIndex: "action",
        fixed: "right",
        slots: { customRender: "action" },
      },
      formConfig: {
        schemas: searchFormSchema,
        fieldMapToTime: [["fieldTime", ["beginDate", "endDate"], "YYYY-MM-DD HH:mm:ss"]],
      },
    },
  })

  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext

  function handleDetail(record) {
    openDetail(true, {
      record,
      isUpdate: true,
    })
  }

  function handleEdit(record: Recordable) {
    openMchDrawer(true, {
      record,
      isUpdate: true,
    })
  }

  function handlePayIfConfig(record: Recordable) {
    openPayIfConfigDrawer(true, {
      mchApp: record,
    })
  }

  function getActions(record) {
    return [
      {
        label: "删除",
        color: "error",
        ifShow: !record.bindTenant,
        popConfirm: {
          title: "是否确认删除",
          confirm: handleDelete.bind(null, record),
        },
      },
      {
        label: "查看",
        onClick: handleDetail.bind(null, record),
        // ifShow: record.sendStatus == 0
      },
      {
        label: "配置",
        // 支付接口配置
        onClick: handlePayIfConfig.bind(null, record),
        // ifShow: record.sendStatus == 0
      },
      {
        label: "编辑",
        onClick: handleEdit.bind(null, record),
        // ifShow: record.sendStatus == 0
      },
    ]
  }

  const handleOpenCashierConfig = () => {
    console.log("selectedRowKeys", selectedRowKeys)
    if (selectedRowKeys.value.length !== 1) {
      createMessage.warn("请选择应用且只能选择一个")
      return
    }
    openCashierConfig(true, {
      appId: unref(selectedRowKeys)[0],
    })
  }

  const handleDelete = async (record) => {
    await deleteMchApp({ mchNo: record.mchNo, appId: record.id }, () => {
      reload()
      createMessage.success("删除成功")
    })
  }

  async function batchHandleDelete() {
    await batchDeleteMchApp({ ids: selectedRowKeys.value }, () => {
      reload()
      createMessage.success("删除成功")
    })
  }

  function handleCreate() {
    openMchDrawer(true, {
      mchNo,
      isUpdate: false,
    })
  }

  const handleTennatBindPayMchApp = async () => {
    createMessage.loading({
      content: "应用初始化中...",
      key: "payAppLoading",
    })
    try {
      const data = await currentTenantBindApp()
      userStore.setSelectTenant({
        ...userStore.getSelectTenant,
        payMchId: data.payMchId,
        payAppId: data.payAppId,
      })
      createMessage.success("应用初始化成功")
      reload()
    } finally {
      createMessage.destroy("payAppLoading")
    }
  }
</script>
